﻿using CozeDomain.Entities;
using CozeDomain.IRepositories;
using CozeDto.SaleApplyForDtos;
using CozeDto.SaleHistoryDtos;
using D.UtilFreesqlOrm;


namespace CozeDomain.Repositories
{
    public class SaleHistoryEntityRepository : BaseRepository<SaleHistoryEntity>, ISaleHistoryEntityRepository
    {
        public SaleHistoryEntityRepository(IFreeSql db) : base(db)
        {
        }

        public async Task<Tuple<long, List<RepSaleHistoryInfo>>> QuerySaleHistoryPagesAsync(ReqQuerySaleHistoryPage reqQuerySaleHistoryPage)
        {
            var where = _db.Select<SaleHistoryEntity, UserEntity>()
                                                         .LeftJoin((a, b) => a.BuyUserId == b.Id)
                                                         .Where((a, b) => a.TenantId == reqQuerySaleHistoryPage.TenantId)
                                                         .WhereIf(!string.IsNullOrEmpty(reqQuerySaleHistoryPage.Account), (a, b) => b.Account.Contains(reqQuerySaleHistoryPage.Account));

            var dbres = await where.Count(out var totalCount)
                                                      .Page(reqQuerySaleHistoryPage.PageNo, reqQuerySaleHistoryPage.PageSize)
                                                      .ToListAsync((a, b) => new RepSaleHistoryInfo
                                                      {
                                                          Account = b.Account,
                                                          CashbackAmount = a.CashbackAmount,
                                                          CashbackAmountLimit = a.CashbackAmountLimit,
                                                          Name = a.Name,
                                                          Price = a.Price,
                                                          CreateTime = a.CreateTime,
                                                          CreateUser = a.CreateUser,
                                                          Id = a.Id,
                                                          UpdateTime = a.UpdateTime,
                                                          UpdateUser = a.UpdateUser
                                                      });

            return new Tuple<long, List<RepSaleHistoryInfo>>(totalCount, dbres);
        }
    }
}
